/**
 * @description 常用工具封装
 * @author zr
 *
 */

import axios from 'axios'

/**
 * 创建时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      // 兼容处理
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * 获取指定年份的上一年
 */
export const getAssignYearLastYear = (value) => {
  const date = new Date()
  date.setFullYear(value)
  return date.getFullYear() - 1
}

/**
 * 获取当前时间
 */
export const getNowTime = (typ) => {
  const now = new Date()
  const year = now.getFullYear() // 年
  const month = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1 // 月
  const day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate() // 日
  let clock = `${year}`
  if (typ === 'day') {
    clock = `${year}-${month}-${day}`
  } else if (typ === 'month') {
    clock = `${year}-${month}`
  }
  return clock
}

/**
 * 格式化时间
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * 获取禁用时间
 * @param {string} startTime
 * @returns {Object}
 */
export function getDisabledTime(startTime) {
  let obj = {}
  if (startTime !== '') {
    obj = {
      disabledDate: (time) => {
        return time.getTime() < new Date(startTime).getTime()
      }
    }
  }
  return obj
}

/**
 * 获取指定时间增加秒数
 * @param {string} d 时间 yyyy-MM-dd HH:mm:ss
 * @param {Number} num 秒
 */
export const getTimeAddSecond = (d, num) => {
  const time = new Date(d)
  time.setTime(time.getTime() + num * 1000)
  const year = time.getFullYear() // 年
  const month = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1 // 月
  const day = time.getDate() < 10 ? '0' + time.getDate() : time.getDate() // 日
  const hour = time.getHours() < 10 ? '0' + time.getHours() : time.getHours() // 时
  const minute = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes() // 分
  const second = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds() // 秒
  // console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`)
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

/**
 * 获取时间差 秒数
 * @param {string} start 开始时间 yyyy-MM-dd HH:mm:ss
 * @param {string} end 结束时间 yyyy-MM-dd HH:mm:ss
 */
export const getTimeDifference = (start, end) => {
  const sTime = new Date(start)
  const eTime = new Date(end)
  const Difference = eTime.getTime() - sTime.getTime()
  return Difference
}

/**
 * 字符串参数转对象
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 16进制图片转rgba
 *
 * @export
 * @param {String} hex 16进制
 * @param {String} a 透明度
 * @return {*}  rgba 字符串
 */

export function hexToRgb(hex, a) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? `rgba(${parseInt(result[1], 16)},${parseInt(result[2], 16)},${parseInt(result[3], 16)}, ${a})` : null
}


/**
 * 导出 GET方式
 * @param {String} url      导出接口地址 拼前缀'/DataExcavate'+
 * @param {Object} param    导出所需对象参数
 * @param {String} fileName 文件名称
 * @return {*}
 */
export const exportFile = (url, param, fileName) => {
  axios
    .get(`${process.env.VUE_APP_BASE_API}` + url, {
      params: param,
      responseType: 'arraybuffer'
    })
    .then((response) => {
      // 创建一个blob对象
      const blob = new Blob([response.data], { type: 'application/x-xls' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      // 配置下载的文件名
      link.download = fileName + '.xls'
      link.click()
    })
}

/**
 * 级联最后一级判空
 */

export const setTreeData = (data) => {
  for (var i = 0; i < data.length; i++) {
    if (data[i].subList.length < 1) {
      data[i].subList = undefined
    } else {
      setTreeData(data[i].subList)
    }
  }
  return data
}

/**
 * 根据最后一级id获取父级相关id
 * @param {String} key      最后一级id
 * @param {Object} treeData    级联下拉数据
 * @return {*}
 */

export const changeDetSelect = (key, treeData) => {
  const arr = []
  const code = []
  let returnArr = []
  let returnCode = []
  let depth = 0
  function childrenEach(childrenData, depthN) {
    for (var j = 0; j < childrenData.length; j++) {
      depth = depthN // 将执行的层级赋值 到 全局层级
      arr[depthN] = childrenData[j].id
      code[depthN] = childrenData[j].code
      // eslint-disable-next-line eqeqeq
      if (childrenData[j].id == key) {
        returnArr = arr.slice(0, depthN + 1) // 将目前匹配的数组，截断并保存到结果数组，
        returnCode = code.slice(0, depthN + 1)
        break
      } else {
        if (childrenData[j].subList) {
          depth++
          childrenEach(childrenData[j].subList, depth)
        }
      }
    }
    return { returnArr, returnCode }
  }
  return childrenEach(treeData, depth)
}

/**
 * 根据最后一级id获取父级相关id
 * @param {String} key      最后一级id
 * @param {Object} treeData    级联下拉数据
 * @return {*}
 */

export const assignObj = (obj, params) => {
  const keyArr = []
  for (var key in obj) {
    keyArr.push(key)
  }
  keyArr.forEach((item) => {
    obj[item] = params[item]
  })
  return obj
}

/**
 * 获取下拉框code对应的name
 */
export const getOptionName = (code, optionData) => {
  let optionObject = {}
  optionObject = optionData.filter((item) => {
    return item.code === code
  })
  const name = optionObject[0].name
  return name
}
